package com.smarthospital.web.inteceptor;

import com.smarthospital.common.Result.CodeMsg;
import com.smarthospital.common.Result.CommonException;
import com.smarthospital.common.util.SpringContextUtil;
import com.smarthospital.dao.daoService.UserDaoService;
import com.smarthospital.entity.pojo.User;
import com.smarthospital.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * create by sym  2021/4/24 10:29.
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static String NO_LOGIN = "no_login";

    private static String[] NO_TOKEN_URIS = {
        ".*swagger.*",
        ".*html.*",
        ".*test.*",
        ".*file.*",
       ".*websocket.*",
       ".*/payCallBack.*",   //支付回调没有登录态
        "/",
        "/webjars.*",
        "/error",
        "/csrf",
        ".*/out/api.*",
        ".*/weChat/login.*"
    };

    public static ThreadLocal<User> ThreadLocal_User = new ThreadLocal<>();

    @Autowired
    private LoginService loginService;

    private static UserDaoService userDaoService;

    private static String isLogin;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String servletPath = request.getServletPath();
        isLogin = SpringContextUtil.getApplicationContext().getEnvironment().getProperty("isLogin");
        if (NO_LOGIN.equals(isLogin)) {
            return true;
        }
        //放行
        for (String uri : NO_TOKEN_URIS) {
            if (servletPath.matches(uri)) {
                log.info("【登录拦截器】 NO_TOKEN  uri {} servletPath {}",uri,servletPath);
                return true;
            }
        }
        log.info("【登录拦截器】 拦截 servletPath {}",servletPath);
        //登录态校验
        User user = loginService.checkToken(request);
        ThreadLocal_User.set(user);
        return true;
    }

    public static User getUser(){
        if (NO_LOGIN.equals(isLogin)) {
            if (userDaoService == null) {
                userDaoService = SpringContextUtil.getBean(UserDaoService.class);

            }
            return userDaoService.selectById(156L);
        }
        User user = ThreadLocal_User.get();
        if (null ==user) {
            throw new CommonException(CodeMsg.ERROR_LOGIN);
        }
        return user;
    }
}
